package com.chixing.server;

import org.apache.tomcat.websocket.WsSession;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.stereotype.Component;

import javax.websocket.Session;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Component
public class RedisKeyExpirationListener extends KeyExpirationEventMessageListener {
    public RedisKeyExpirationListener(RedisMessageListenerContainer listenerContainer) {
        super(listenerContainer);
    }
    /**
     * 针对redis数据失效事件，进行数据处理
     * @param message
     * @param pattern
     */
    @Autowired
    RabbitTemplate rabbitTemplate;
    @Autowired
    WebSocketServerEndpoint webSocketServerEndpoint;
    @Override
    public void onMessage(Message message, byte[] pattern) {
        // 用户做自己的业务处理即可,注意message.toString()可以获取失效的key
        String expiredKey = message.toString();
        System.out.println("失效了一个Redis数据");
        Map<String,Object> map = new HashMap<>();
        map.put("hello",new Date());
        // WebSocket测试
        webSocketServerEndpoint.sendMessageOnline("hesdfsfllo");
        rabbitTemplate.convertAndSend("TestDirectExchange","TestDirectRouting",map);
        System.out.println(expiredKey);
    }
}